//
//  LDSRouterInfo.m
//  DoorBell
//
//  Created by Chun Hung Cheung on 2024/7/26.
//  Copyright © 2024 Chun Hung Cheung. All rights reserved.
//
#import "LDSRouterInfo.h"
#import <ifaddrs.h>
#import <arpa/inet.h>

#include <stdio.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <sys/sysctl.h>
#include "getgateway.h"
#include "route.h"
#include <net/if.h>
#include <string.h>

@implementation LDSRouterInfo
+ (NSDictionary *)getRouterInfo {
    NSMutableDictionary *router = @{}.mutableCopy;
    
    NSString *address = nil;
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;

    success = getifaddrs(&interfaces);
    
    if (success == 0) {

        temp_addr = interfaces;
        
        while(temp_addr != NULL) {
            
            if(temp_addr->ifa_addr->sa_family == AF_INET) {

                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    NSString *netmask = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_netmask)->sin_addr)];
                    NSLog(@"子网掩码:%@",netmask);
                    NSString *ip = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                    NSLog(@"本地IP:%@",ip);
                    NSString *boardCast = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)];
                    NSLog(@"广播地址:%@",boardCast);
                    
                    [router setObject:netmask?:@"" forKey:@"subnetMask"];
                    [router setObject:ip?:@"" forKey:@"ip"];
                    [router setObject:boardCast?:@"" forKey:@"dns"];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    freeifaddrs(interfaces);
    struct in_addr addr;
    NSString * addrStr = @"";
    if (getdefaultgateway(&(addr.s_addr)) == 0)
    {
        addrStr = [NSString stringWithUTF8String:inet_ntoa(addr)];
    }
    [router setObject:addrStr forKey:@"router"];
    
    return router.copy;
}


@end

